<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 新疆奎木星测控技术有限公司</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <style>
        body {
            margin: 0;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
            background-color: #f5f5f5;
        }
        
        .container {
            padding: 20px;
        }
        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .search-form {
            margin-bottom: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 6px;
        }
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="page-container">
            <!-- 页面头部 -->
            <div class="page-header">
                <h1 class="page-title">
                    <i class="fas fa-users"></i> 用户管理
                </h1>
                <p class="page-subtitle">管理系统用户账号、角色权限和状态信息</p>
            </div>
            
            <!-- 主要内容区域 -->
            <div class="content-card">
                <!-- 卡片头部 -->
                <div class="card-header">
                    <h2 class="card-title">用户列表</h2>
                    <el-button type="primary" @click="showAddDialog = true">
                        <i class="fas fa-plus"></i> 新增用户
                    </el-button>
                </div>
                
                <!-- 搜索表单（基于新的数据库结构） -->
                <div class="search-form">
                    <el-form :model="searchForm" :inline="true">
                        <el-form-item label="姓名">
                            <el-input v-model="searchForm.name" placeholder="请输入真实姓名" clearable style="width: 200px;"></el-input>
                        </el-form-item>
                        <el-form-item label="身份证号">
                            <el-input v-model="searchForm.idCard" placeholder="请输入身份证号" clearable style="width: 200px;"></el-input>
                        </el-form-item>
                        <el-form-item label="用户名">
                            <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable style="width: 150px;"></el-input>
                        </el-form-item>
                        <el-form-item label="角色">
                            <el-select v-model="searchForm.roleName" placeholder="请选择角色" clearable style="width: 150px;">
                                <el-option v-for="role in roleOptions" :key="role.id" :label="role.roleName" :value="role.roleName"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="实体类型">
                            <el-select v-model="searchForm.entityType" placeholder="请选择实体类型" clearable style="width: 150px;">
                                <el-option v-for="entity in entityTypeOptions" :key="entity.value" :label="entity.label" :value="entity.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="searchUsers">
                                <i class="fas fa-search"></i> 搜索
                            </el-button>
                            <el-button @click="resetSearch">
                                <i class="fas fa-redo"></i> 重置
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
                
                <!-- 用户表格（基于新的数据库结构） -->
                <div class="table-container">
                    <el-table :data="filteredUsers" style="width: 100%" stripe>
                        <el-table-column prop="id" label="ID" width="80"></el-table-column>
                        <el-table-column prop="name" label="真实姓名" width="120"></el-table-column>
                        <el-table-column prop="idCard" label="身份证号" width="180"></el-table-column>
                        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
                        <el-table-column prop="roleName" label="角色" width="120">
                            <template #default="scope">
                                <el-tag v-if="scope.row.roleName === '系统管理员'" type="danger">{{ scope.row.roleName }}</el-tag>
                                <el-tag v-else-if="scope.row.roleName === '集团管理员'" type="warning">{{ scope.row.roleName }}</el-tag>
                                <el-tag v-else-if="scope.row.roleName === '加工厂管理员'" type="primary">{{ scope.row.roleName }}</el-tag>
                                <el-tag v-else type="info">{{ scope.row.roleName }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="管理范围" width="150">
                            <template #default="scope">
                                <el-tag size="small" effect="plain">{{ getEntityTypeLabel(scope.row.entityType) }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="entityName" label="管理实体" width="180"></el-table-column>
                        <el-table-column prop="createdAt" label="创建时间" width="160"></el-table-column>
                        <el-table-column label="操作" width="200" fixed="right">
                            <template #default="scope">
                                <div class="action-buttons">
                                    <el-button size="small" class="btn-edit" @click="editUser(scope.row)">
                                        <i class="fas fa-edit"></i> 编辑
                                    </el-button>
                                    <el-button size="small" class="btn-delete" @click="deleteUser(scope.row)">
                                        <i class="fas fa-trash"></i> 删除
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                
                <!-- 分页 -->
                <div class="pagination-container">
                    <el-pagination
                        v-model:current-page="currentPage"
                        v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="totalUsers"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    >
                    </el-pagination>
                </div>
            </div>
        </div>
        
        <!-- 新增/编辑用户对话框（基于新的数据库结构） -->
        <el-dialog v-model="showAddDialog" :title="editingUser ? '编辑用户' : '新增用户'" width="600px">
            <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
                <el-form-item label="真实姓名" prop="name">
                    <el-input v-model="userForm.name" placeholder="请输入真实姓名"></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="idCard">
                    <el-input v-model="userForm.idCard" placeholder="请输入身份证号" maxlength="18"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!editingUser">
                    <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="userForm.roleId" placeholder="请选择角色" style="width: 100%;">
                        <el-option v-for="role in roleOptions" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="实体类型" prop="entityType">
                    <el-select v-model="userForm.entityType" placeholder="请选择实体类型" style="width: 100%;">
                        <el-option v-for="entity in entityTypeOptions" :key="entity.value" :label="entity.label" :value="entity.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="管理实体" prop="entityId" v-if="userForm.entityType">
                    <el-select v-model="userForm.entityId" placeholder="请选择具体的管理实体" style="width: 100%;">
                        <el-option v-for="entity in getEntityOptions(userForm.entityType)" :key="entity.id" :label="entity.name" :value="entity.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveUser">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    
    <script>
        const { createApp } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;
        
        createApp({
            data() {
                return {
                    // 搜索表单数据（基于新的数据库结构）
                    searchForm: {
                        name: '',
                        idCard: '',
                        username: '',
                        roleName: '',
                        entityType: ''
                    },
                    // 用户表单数据（基于User、Account、Role表结构）
                    userForm: {
                        id: null,
                        name: '',
                        idCard: '',
                        username: '',
                        password: '',
                        roleId: null,
                        entityType: '',
                        entityId: null
                    },
                    // 表单验证规则（基于新的数据库字段）
                    userRules: {
                        name: [
                            { required: true, message: '请输入真实姓名', trigger: 'blur' },
                            { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
                        ],
                        idCard: [
                            { required: true, message: '请输入身份证号', trigger: 'blur' },
                            { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
                        ],
                        username: [
                            { required: true, message: '请输入用户名', trigger: 'blur' },
                            { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
                        ],
                        password: [
                            { required: true, message: '请输入密码', trigger: 'blur' },
                            { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
                        ],
                        roleId: [
                            { required: true, message: '请选择角色', trigger: 'change' }
                        ],
                        entityType: [
                            { required: true, message: '请选择实体类型', trigger: 'change' }
                        ]
                    },
                    
                    // 角色选项（基于Role表）
                    roleOptions: [
                        { id: 1, roleName: '系统管理员' },
                        { id: 2, roleName: '集团管理员' },
                        { id: 3, roleName: '加工厂管理员' },
                        { id: 4, roleName: '数据录入员' },
                        { id: 5, roleName: '数据查看员' }
                    ],
                    
                    // 实体类型选项（基于Account_Entity_Relation表）
                    entityTypeOptions: [
                        { value: 'province', label: '省/兵团' },
                        { value: 'city', label: '市' },
                        { value: 'district', label: '区/县/师' },
                        { value: 'township', label: '乡/团' },
                        { value: 'village', label: '村/连' },
                        { value: 'group', label: '集团' },
                        { value: 'factory', label: '加工厂' },
                        { value: 'Troop', label: '兵团' }
                    ],
                    // 对话框显示状态
                    showAddDialog: false,
                    editingUser: null,
                    // 分页数据
                    currentPage: 1,
                    pageSize: 10,
                    totalUsers: 0,
                    // 用户数据（基于User表和Account表的结构）
                    users: [
                        {
                            id: 1,
                            name: '张三',
                            idCard: '110101199001011234',
                            username: 'zhangsan',
                            roleName: '系统管理员',
                            entityType: 'province',
                            entityName: '新疆维吾尔自治区',
                            createdAt: '2024-01-15 10:30:00'
                        },
                        {
                            id: 2,
                            name: '李四',
                            idCard: '110101199002021234',
                            username: 'lisi',
                            roleName: '集团管理员',
                            entityType: 'group',
                            entityName: '新疆奎木星集团',
                            createdAt: '2024-01-16 14:20:00'
                        },
                        {
                            id: 3,
                            name: '王五',
                            idCard: '110101199003031234',
                            username: 'wangwu',
                            roleName: '加工厂管理员',
                            entityType: 'factory',
                            entityName: '奎木星第一加工厂',
                            createdAt: '2024-01-17 09:15:00'
                        },
                        {
                            id: 4,
                            name: '赵六',
                            idCard: '110101199004041234',
                            username: 'zhaoliu',
                            roleName: '数据录入员',
                            entityType: 'village',
                            entityName: '石河子市第一连',
                            createdAt: '2024-01-18 16:45:00'
                        }
                    ]
                }
            },
            computed: {
                // 过滤后的用户列表（基于新的搜索条件）
                filteredUsers() {
                    let filtered = this.users;
                    
                    // 按姓名过滤
                    if (this.searchForm.name) {
                        filtered = filtered.filter(user => 
                            user.name.includes(this.searchForm.name)
                        );
                    }
                    
                    // 按身份证号过滤
                    if (this.searchForm.idCard) {
                        filtered = filtered.filter(user => user.idCard.includes(this.searchForm.idCard));
                    }
                    
                    // 按用户名过滤
                    if (this.searchForm.username) {
                        filtered = filtered.filter(user => user.username.includes(this.searchForm.username));
                    }
                    
                    // 按角色过滤
                    if (this.searchForm.roleName) {
                        filtered = filtered.filter(user => user.roleName === this.searchForm.roleName);
                    }
                    
                    // 按实体类型过滤
                    if (this.searchForm.entityType) {
                        filtered = filtered.filter(user => user.entityType === this.searchForm.entityType);
                    }
                    
                    this.totalUsers = filtered.length;
                    
                    // 分页处理
                    const start = (this.currentPage - 1) * this.pageSize;
                    const end = start + this.pageSize;
                    return filtered.slice(start, end);
                }
            },
            methods: {
                // 搜索用户
                searchUsers() {
                    this.currentPage = 1;
                    ElMessage.success('搜索完成');
                },
                
                // 重置搜索（基于新的字段结构）
                resetSearch() {
                    this.searchForm = {
                        name: '',
                        idCard: '',
                        username: '',
                        roleName: '',
                        entityType: ''
                    };
                    this.currentPage = 1;
                    ElMessage.info('搜索条件已重置');
                },
                
                // 编辑用户（基于新的数据结构）
                editUser(user) {
                    this.editingUser = user;
                    // 根据角色名称找到对应的角色ID
                    const role = this.roleOptions.find(r => r.roleName === user.roleName);
                    this.userForm = {
                        id: user.id,
                        name: user.name,
                        idCard: user.idCard,
                        username: user.username,
                        password: '', // 编辑时不显示密码
                        roleId: role ? role.id : null,
                        entityType: user.entityType,
                        entityId: user.entityId || null
                    };
                    this.showAddDialog = true;
                },
                
                // 删除用户
                deleteUser(user) {
                    ElMessageBox.confirm(
                        `确定要删除用户 "${user.name}" 吗？`,
                        '删除确认',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(() => {
                        const index = this.users.findIndex(u => u.id === user.id);
                        if (index > -1) {
                            this.users.splice(index, 1);
                            ElMessage.success('删除成功');
                        }
                    }).catch(() => {
                        ElMessage.info('已取消删除');
                    });
                },
                
                // 保存用户（基于新的数据库结构）
                saveUser() {
                    this.$refs.userFormRef.validate((valid) => {
                        if (valid) {
                            if (this.editingUser) {
                                // 编辑模式
                                const index = this.users.findIndex(u => u.id === this.editingUser.id);
                                if (index > -1) {
                                    const role = this.roleOptions.find(r => r.id === this.userForm.roleId);
                                    this.users[index] = {
                                        ...this.userForm,
                                        id: this.editingUser.id,
                                        roleName: role ? role.roleName : '',
                                        entityName: this.getEntityName(this.userForm.entityType, this.userForm.entityId),
                                        createdAt: this.editingUser.createdAt
                                    };
                                    ElMessage.success('用户信息更新成功');
                                }
                            } else {
                                // 新增模式
                                const role = this.roleOptions.find(r => r.id === this.userForm.roleId);
                                const newUser = {
                                    ...this.userForm,
                                    id: this.users.length + 1,
                                    roleName: role ? role.roleName : '',
                                    entityName: this.getEntityName(this.userForm.entityType, this.userForm.entityId),
                                    createdAt: new Date().toLocaleString()
                                };
                                this.users.push(newUser);
                                ElMessage.success('用户创建成功');
                            }
                            
                            this.showAddDialog = false;
                            this.editingUser = null;
                            this.resetUserForm();
                        }
                    });
                },
                
                // 重置用户表单（基于新的数据库结构）
                resetUserForm() {
                    this.userForm = {
                        id: null,
                        name: '',
                        idCard: '',
                        username: '',
                        password: '',
                        roleId: null,
                        entityType: '',
                        entityId: null
                    };
                },
                
                // 分页处理
                handleSizeChange(val) {
                    this.pageSize = val;
                    this.currentPage = 1;
                },
                
                handleCurrentChange(val) {
                    this.currentPage = val;
                },
                
                // 获取实体类型标签
                getEntityTypeLabel(entityType) {
                    const entity = this.entityTypeOptions.find(e => e.value === entityType);
                    return entity ? entity.label : entityType;
                },
                
                // 根据实体类型获取实体选项
                getEntityOptions(entityType) {
                    // 这里应该根据实体类型从后端获取对应的实体列表
                    // 暂时返回模拟数据
                    const mockData = {
                        'province': [{ id: 1, name: '新疆维吾尔自治区' }],
                        'group': [{ id: 1, name: '新疆奎木星集团' }],
                        'factory': [{ id: 1, name: '奎木星第一加工厂' }, { id: 2, name: '奎木星第二加工厂' }],
                        'village': [{ id: 1, name: '石河子市第一连' }, { id: 2, name: '石河子市第二连' }]
                    };
                    return mockData[entityType] || [];
                },
                
                // 获取实体名称
                getEntityName(entityType, entityId) {
                    const options = this.getEntityOptions(entityType);
                    const entity = options.find(e => e.id === entityId);
                    return entity ? entity.name : '';
                }
            },
            
            mounted() {
                this.totalUsers = this.users.length;
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>